import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_shape.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/module/task/page/task_detail_page.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/status_utils.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'pop_stations_list.dart';



class PopTrackStatus extends StatefulWidget {
  int id;
  String title;
  PopTrackStatus(this.id, {this.title = ""});

  @override
  State<StatefulWidget> createState() {
    return PopCarStatusState();
  }
}

class PopCarStatusState extends State<PopTrackStatus> {
  dynamic _data;
  final _describeTextController = TextEditingController();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final StateLayoutController _stateLayoutController = StateLayoutController();
  //var isError = false;
  var _type = 0;
  bool _showDispatch = false;
  late StreamSubscription _eventFn1;

  @override
  void initState() {
    super.initState();

    initButton();

    _eventFn1 = eventBus.on<ChangeStationsEvent>().listen((event) {
      _stateLayoutController.reload();
    });

  }

  @override
  void dispose() {
    super.dispose();
    _eventFn1.cancel();
  }

  @override
  Widget build(BuildContext context) {
    var sw = MediaQuery.of(context).size.height;
    var height = sw * 0.7;

    if (MediaQuery.of(context).viewInsets.bottom > sw * 0.2) {
      height = sw * 0.9 - MediaQuery.of(context).viewInsets.bottom;
    }
    return Container(
        //height: height,
        //margin: EdgeInsets.only(right: 0.1.rpx),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
        ),
        child:
        Column(
          children: [
            8.hspace,
            Container(
              width: 36.rpx,
              height: 5.rpx,
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.26),
                borderRadius: BorderRadius.circular(2.rpx),
              ),
            ),
            //isError?_renderErrorTitle():_renderTitle(),
            //isError?_renderErrorInfo():
            Expanded(
              child: StateLayout(
                url: "/car/detail?id=${widget.id}",
                controller: _stateLayoutController,
                childBuilder: _renderContent,
                dataCallback: (data) {
                  _data = data;
                },
              ),
            ),
          ],
        ),
    );
  }

  // Widget _renderErrorTitle() {
  //   String stText = "异常上报";
  //   return  Row(
  //       crossAxisAlignment: CrossAxisAlignment.center,
  //       children: [
  //         TextButton(onPressed: _onReturn,
  //             child: SvgPicture.asset(R.image_left, width: 24.rpx, height: 24.rpx),
  //         ),
  //         90.wspace,
  //         Expanded(
  //             child: UText.get(stText, Colors.black, 20.rpx, fw: FontWeight.bold)
  //         ),
  //       ]
  //   );
  // }

  Widget _renderErrorInfo() {
    return
      Expanded(
        child: SingleChildScrollView(
          child: Column(
            children: [
              16.hspace,
              Row(
                children: [
                  24.wspace,
                  UText.get("异常类型", Colors.black, 14.rpx),
                  8.wspace,
                  UText.getBkButton("取货异常", 14.rpx,
                    width: 88.rpx,
                    height: 30.rpx,
                    color: _type == 0 ? Colors.white : UIColor.color_t2,
                    bkColor: _type == 0 ?  UIColor.color_primary : UIColor.color_input ,
                    radius: 2.rpx,
                    onPressed: _onClickType),
                  8.wspace,
                  UText.getBkButton("其他", 14.rpx,
                    width: 60.rpx,
                    height: 30.rpx,
                    color: _type == 1 ? Colors.white : UIColor.color_t2,
                    bkColor: _type == 1 ?  UIColor.color_primary : UIColor.color_input ,
                    radius: 2.rpx,
                    onPressed: _onClickType)
                ]
              ),
              24.hspace,
              Row(
                children: [
                  24.wspace,
                  UText.get("异常描述", Colors.black, 14.rpx),
              ]),
              Row(
                children: [
                  24.wspace,
                  Expanded(
                      child: TextField(
                          controller: _describeTextController,
                          keyboardType: TextInputType.multiline,
                          maxLines: null,
                          maxLength: 500,
                          decoration: const InputDecoration(
                            hintText: "请输入异常描述",
                          )
                      )
                  ),
                  24.wspace,
                ]
              ),
              24.hspace,
              Row(
                children: [
                  16.wspace,
                  Expanded(
                    child: UText.getBkButton("提交", 14.rpx,
                      width: 343.rpx,
                      height: 40.rpx,
                      bkColor: UIColor.color_primary,
                      radius: 4.rpx,
                      onPressed: _onSubmit)
                  ),
                  16.wspace,
                ]
              ),
              24.hspace,
            ]
          )
        )
      );
      Row(
        children: [
        24.wspace,
        UText.get("异常类型", Colors.black.withOpacity(0.4), 14.rpx),
        8.wspace,
        Expanded(
            child: UText.get(StatusUtils.getDriveMode(_data["drive_mode"]), Colors.black, 14.rpx)
        ),
      ]
    );
  }

  Widget _renderTitle() {
    String stText = " ";
    if (_data != null) {
      if (_data["status"] == 3) {
        stText = " 任务中";
      } else if (_data["status"] == 2 || _data["status"] == 5) {
        stText = " 空闲中";
      } else if (_data["status"] == 4) {
        stText = " 调配中";
      }else if (_data["status"] == -1) {
        stText = " 不可用";
      }
    }
    return Container(
      height: 48.rpx,
      alignment: Alignment.center,
      child: UText.get(widget.title + stText, Colors.black, 20.rpx, fw: FontWeight.bold),
    );
  }

  Widget _renderContent(dynamic data) {
    _data = data;

    return SingleChildScrollView(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _renderTitle(),
        ..._renderCarInfo(),
        16.hspace,
        ..._getTaskTrack()
      ],
    ));
  }

  List<Widget> _renderCarInfo() {
    return [
      Row(
        children: [
          24.wspace,
          UText.get("当前模式", Colors.black.withOpacity(0.4), 14.rpx),
          8.wspace,
          Expanded(
              child: UText.get(StatusUtils.getDriveMode(_data["drive_mode"]), Colors.black, 14.rpx)
          ),
          16.wspace,
          // _data["status"] == 3
          //   ?Container(
          //   margin: EdgeInsets.symmetric(horizontal: 16.rpx),
          //   child: TextButton(onPressed: _onClickUnusual,
          //       child: UText.get("异常", UIColor.color_none, 14.rpx)),
          // ):0.wspace
        ],
      ),
      12.hspace,
      // Row(
      //   children: [
      //     24.WSpace,
      //     UText.get("电量        ", Colors.black.withOpacity(0.4), 14.rpx),
      //     8.WSpace,
      //     UText.get("${_data["electricity"]}%", Colors.black, 14.rpx),
      //   ],
      // ),
      // 12.HSpace,
      // Row(
      //   children: [
      //     24.WSpace,
      //     UText.get("速度        ", Colors.black.withOpacity(0.4), 14.rpx),
      //     8.WSpace,
      //     UText.get("${_data["speed"]}m/s", Colors.black, 14.rpx),
      //   ],
      // ),
      // 12.HSpace,
      Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          _data["status"] == 4?
          Row(
            children: [
            UText.get("预计到达时间", Colors.black.withOpacity(0.4), 14.rpx),
            8.wspace,
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UText.get(_data["estimate_time"].toString(), Colors.black, 14.rpx)
              ]
            )
          ])
          :
          Row(
            children: [
              UText.get("车辆位置", Colors.black.withOpacity(0.4), 14.rpx),
              8.wspace,
              UText.get(_data["station"].toString(), Colors.black, 14.rpx)
          ])
      ])
    ];
  }

  List<Widget> _getTaskTrack() {
    Widget content;
    int st = _data["waybill_operation"];

    if(_data["status"] == 2) {
      return [
        32.hspace,
        Row(
            children: [
              20.wspace,
              Expanded(
                  child: _showDispatch?UText.getBkButton("开始调车", 14.rpx,
                    width: 343.rpx,
                    height: 40.rpx,
                    bkColor: UIColor.color_primary,
                    radius: 4.rpx,
                    onPressed:  () {
                      OpenUtils.pop2(context, PopStationsList(_data['lat'],_data['lng'],_data['car_no'],StatusUtils.getDriveMode(_data["drive_mode"]),_data["status"],_data["id"],1));
                    }):0.wspace
              ),
              20.wspace,
            ]
        )
      ];
    }
    if(_data["status"] == 4) {
      return [
        32.hspace,
        Row(
            children: [
              20.wspace,
              Expanded(
                  child: UText.getBkButton("变更终点", 14.rpx,
                      width: 343.rpx,
                      height: 40.rpx,
                      bkColor: UIColor.color_primary,
                      radius: 4.rpx,
                      onPressed: () {
                        CustomAlertDialog.show(context,  content: "确定变更终点?",  onConfirm: () {
                          OpenUtils.pop2(context, PopStationsList(_data['lat'],_data['lng'],_data['car_no'],StatusUtils.getDriveMode(_data["drive_mode"]),_data["status"],_data["id"],2));
                        });
                      },)
              ),
              20.wspace,
            ]
        )
      ];
    }
    if (st == 0 || st == -1) {
      return [0.hspace];
    }
    Widget rightWidget;
    if (st == -1) {
      rightWidget = UText.get("已取消", UIColor.color_t3, 14.rpx);
    } else if (st == 3) {
      rightWidget = UText.get("已完成", UIColor.color_t3, 14.rpx);
    } else {
      rightWidget = 0.wspace;
    }
    return [
      Container(
        color: UIColor.color_divider,
        height: 0.5.rpx,
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 16.rpx),
      ),
      16.hspace,
      Padding(
        padding: EdgeInsets.only(left: 24.rpx),
        child: UText.get("任务路线", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
      ),
      8.hspace,
      Row(
        children: [
          24.wspace,
          UText.getSubText("任务编号"),
          8.wspace,
          GestureDetector(
            onTap: () {
              OpenUtils.open(context, TaskDetailPage(_data["waybill_no"]));
            },
            child: Text(
              _data["waybill_no"].toString(),
              style: TextStyle(
                fontSize: 14.rpx,
                color: UIColor.color_primary,
                decoration: TextDecoration.underline,
                decorationColor: UIColor.color_primary,
              ),
            ),
          ),
          8.wspace,
          rightWidget,
        ],
      ),
      10.hspace,
      _renderLoadWrap(),
      _renderUnLoadWrap()
    ];
  }

  String _buildUrl() {
    var baseUrl = "/waybill/list?status=";
    var searchKey = "";
    if (searchKey.isNotEmpty) {
      if (!baseUrl.contains("?")) {
        baseUrl += "?";
      } else {
        baseUrl += "&";
      }
      baseUrl += "search_key=${Uri.encodeComponent(searchKey)}";
    }
    return baseUrl;
  }

  Widget test() {
    return Container(
        color: UIColor.color_content,
        padding: EdgeInsets.symmetric(
          horizontal: 16.rpx,
        ),
        child:Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              UText.get("终点", UIColor.color_t1, 16.rpx),
              8.wspace,
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
                  padding: EdgeInsets.only(left: 10.rpx, top: 10.rpx, right: 10.rpx, bottom: 10.rpx),
                  decoration: BoxDecoration(
                    color: Color(0xffE7E7E7),
                    borderRadius: BorderRadius.vertical(top: Radius.circular(4.rpx), bottom: Radius.circular(4.rpx)),
                  ),
                  child: UText.get('B2路口', Colors.black, 16.rpx, fw: FontWeight.bold),
                ),
              )
            ]
        )
    );
  }

  Widget _renderLoadWrap() {
    int st = _data["waybill_operation"];
    int ms = _data["mission_status"];
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          Column(
            children: [
              4.hspace,
              UShape.getCircle(
                  size: 12.rpx, color: ms >= 3? UIColor.color_primary : UIColor.color_content, borderColor: UIColor.color_primary, borderWidth: 1.rpx),
              Expanded(
                child: Container(
                  width: 1.rpx,
                  color: st == 2 || ms >= 5? UIColor.color_primary : const Color(0xffd2d2d2),
                ),
              ),
            ],
          ),
          10.wspace,
          _renderLoad(),
          4.wspace,
        ],
      ),
    );
  }

  Widget _renderUnLoadWrap() {
    int st = _data["waybill_operation"];
    int ms = _data["mission_status"];
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          Column(
            children: [
              Container(
                height: 4.rpx,
                width: 1.rpx,
                color: st == 2 || ms >= 5? UIColor.color_primary : const Color(0xffd2d2d2),
              ),
              UShape.getCircle(
                  size: 12.rpx,
                  color: ms == 7? UIColor.color_primary : UIColor.color_content,
                  borderColor: st == 2 ? UIColor.color_primary : const Color(0xffd2d2d2),
                  borderWidth: 1.rpx),
            ],
          ),
          10.wspace,
          _renderUnload(),
          4.wspace,
        ],
      )
    );
  }

  Widget _renderLoad() {
    int ms = _data["mission_status"];
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderKv("提货点    ", "pick_station_name", ms >= 3 ? UIColor.color_primary : UIColor.color_t1 ),
          5.hspace,
          _renderKv("提货人    ", "pick_username", UIColor.color_t1),
          5.hspace,
          _renderKv("提货电话", "pick_tel", UIColor.color_t1),
          5.hspace,
          _renderKv("提货车牌", "pick_tel", UIColor.color_t1),
          14.hspace,
        ],
      ),
    );
  }

  Widget _renderUnload() {
    int ms = _data["mission_status"];
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderKv("卸货点    ", "delivery_station_name", ms == 7 ? UIColor.color_primary : UIColor.color_t1),
          5.hspace,
          _renderKv("卸货人    ", "delivery_username", UIColor.color_t1),
          5.hspace,
          _renderKv("卸货电话", "delivery_tel", UIColor.color_t1),
          5.hspace,
          _renderKv("卸货车牌", "pick_tel", UIColor.color_t1),
          24.hspace,
        ],
      ),
    );
  }

  Widget _renderKv(String key, String value, Color color) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        UText.getSubText(key),
        12.wspace,
        Expanded(
          child: UText.get(_data[value], color, 14.rpx, fw: FontWeight.w600),
        ),
      ],
    );
  }

  // _onClickLoad() {
  //   OpenUtils.open(context, OrderLoadPage(_data["waybill_no"],_data["status"]));
  // }
  //
  // _onClickUnload() {
  //   OpenUtils.open(context, OrderUnloadPage(_data["waybill_no"],_data["total_weight"],_data["qty"],1,_data["car_no"]));
  // }

  // _onClickUnusual() {
  //   setState(() {
  //     isError = true;
  //   });
  // }

  // _onReturn() {
  //   setState(() {
  //     isError = false;
  //   });
  // }

  _onClickType() {
    setState(() {
      _type = _type == 0?1:0;
    });
  }

  _onSubmit() {
    // var _describeText = _describeTextController.text;
    // if (_describeText.isEmpty) {
    //   Tip.show("异常描述不能为空");
    //   return;
    // }
    var dialog = LoadingDialog(context);
    // dialog.show(text: "提交中...");
    var url = "/waybill/loading2";
    Api.submitx(context, url, data: json, progress: false, success: (data) {
      dialog.hide();
      // setState(() {
      //   isError = false;
      // });
    }, failTip: "提交失败", fail: (_) {
      dialog.hide();
    });
  }

  initButton() async {
    var _sp = await SharedPreferences.getInstance();
    _showDispatch = _sp.getBool("_showDispatch") as bool;
  }
}
